package com.example.gamestore.controller;

import com.example.gamestore.pojo.Game;
import com.example.gamestore.service.GameService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping(value = "search")
public class SearchController {

    private static final Logger logger = LoggerFactory.getLogger(SearchController.class);

    @Autowired
    private GameService gameService; // 使用接口而非实现类

    @GetMapping(value = "")
    public String showSearch(
            @RequestParam(value = "key", required = false) String key,
            HttpSession session,
            Model model) {

        // 从URL或Session获取搜索关键词
        if (key != null && !key.isEmpty()) {
            session.setAttribute("searchKey", key);
        } else {
            key = (String) session.getAttribute("searchKey");
            key = key != null ? key : "";
        }

        // 执行数据库搜索
        List<Game> games = gameService.searchGames(key);
        model.addAttribute("games", games);
        model.addAttribute("searchKey", key);

        logger.info("搜索关键词: " + key + ", 结果数: " + (games != null ? games.size() : 0));
        return "search";
    }
}